<template>
  <!-- 培养观察 -->
  <div id="rptCultiObserResult">
    <el-tabs v-model="activeName" type="card" class="lab-bac-test-result-tab el-tab-sm" @tab-click="tabHandleClick">
      <el-tab-pane label="培养观察" name="first"></el-tab-pane>
      <el-tab-pane label="菌株观察" name="second"></el-tab-pane>
      <el-tab-pane label="过程记录" name="third">过程记录</el-tab-pane>
      <el-tab-pane label="流程单" name="fourth">流程单</el-tab-pane>
      <el-tab-pane label="申请项目" name="fifth"></el-tab-pane>
    </el-tabs>
    <div id="transResult" v-show="activeName === 'first'">
      <vxe-toolbar class-name="bg-grey light">
        <template #buttons>
          <vxe-button type="text" class="button-blue margin-lr-xs" :content="'新增'" @click="addCulResult"
            :disabled='resultIsDisabled()'></vxe-button>
          <vxe-button type="text" class="button-blue margin-lr-xs" :content="'保存'" @click="saveCulResult"
            :disabled='resultIsDisabled()'></vxe-button>
          <vxe-button type="text" class="button-red margin-lr-xs" :content="'删除'" @click="handleDelete"
            :disabled='resultIsDisabled()'></vxe-button>
        </template>
      </vxe-toolbar>
      <vxe-table show-overflow keep-source ref="transResultRef" height="auto"
        :header-cell-style="{ height: '28px', padding: '0px 2px' }" :column-config="{ resizable: true }"
        :loading="loading" :data="transResultList"
        :edit-config="{ trigger: 'click', mode: 'cell', showStatus: false, showIcon: false }">
        <vxe-column type="checkbox" width="30" fixed="left" align="center"></vxe-column>
        <vxe-column title="观察结果" field="obserResult" :edit-render="{}">
          <template #default="{ row }">
            <span>{{ row.obserResult }}</span>
          </template>
          <template #edit="{ row }">
            <vxe-select v-model="row.obserResult" placeholder="请选择结果" clearable transfer>
              <vxe-option v-for="item in obserResultList" :key="item.name" :label="item.name"
                :value="item.name"></vxe-option>
            </vxe-select>
          </template>
        </vxe-column>
        <vxe-column field="createTime" title="操作时间">
          <template #default="{ row }">
            <span>{{ row.createTime }}</span>
          </template>
        </vxe-column>
        <vxe-column field="userName" title="操作人" align="center"></vxe-column>
      </vxe-table>
    </div>
    <div v-show="activeName === 'second'">
      <vxe-toolbar class-name="bg-grey light">
        <template #buttons>
          <vxe-button type="text" class="button-blue margin-lr-xs" :content="'新增'" @click="addStrain"
            :disabled='resultIsDisabled() || loadingAdd'></vxe-button>
          <vxe-button type="text" class="button-blue margin-lr-xs" :content="'批量新增'" @click="addStrainBatch"
                      :disabled='resultIsDisabled() || loadingAdd'></vxe-button>
          <vxe-button type="text" class="button-blue margin-lr-xs" :content="'保存'" @click="save"
            :disabled='resultIsDisabled()'></vxe-button>
          <!-- <vxe-button type="text" class="button-blue margin-lr-xs" :content="'批次阴性'"></vxe-button>
          <vxe-button type="text" class="button-blue margin-lr-xs" :content="'查看病历'"></vxe-button> -->
          <vxe-button type="text" class="button-blue margin-lr-xs" :content="'危急值'" @click="criticalClick"></vxe-button>
          <vxe-button type="text" class="button-red margin-lr-xs" :content="'删除菌株'" @click="deleteStrain"
            :disabled='resultIsDisabled()'></vxe-button>
        </template>
      </vxe-toolbar>
      <div class="radius margin-xs solid line-grey padding-xs">
        <el-steps style="width: 100%" :active="bacActive" align-center>
          <el-step class="text-blue" title="" v-for="(m, i) in bacCultiObserList" :key="i"
            :class="m.isActive ? 'bg-blue light radius' : ''" @click="bacCultiObserItemClick(m)">
            <template #icon>
              <div class="text-blue" :class="m.isActive ? 'text-shadow' : 'text-blue'" style="margin-bottom: 5px">
                <span>第</span>
                <span class="cu-tag margin-lr-xs" style="background: rgba(0, 0, 0, 0)">{{ `${m.strainCode}` }}</span>
                <span>株菌</span>
              </div>
            </template>
          </el-step>
        </el-steps>
      </div>
      <div class="radius solids lines-green padding-xs">
        <Splitpanes>
          <Pane size="80">
            <div class="padding-xs" :class='resultIsDisabled() ? "padding-xs no-edit" : "padding-xs"'>
              <vxe-form ref="formObserRef" :data="formData" title-width="75">
                <vxe-form-item title="结果描述" field="morphologyName" span="24">
                  <template #title>
                    <span class="margin-lr-xs">结果描述</span>
                  </template>
                  <template #default="params">
                    <vxe-textarea v-model="params.data.morphologyName" placeholder="双击编辑结果描述"
                      @dblclick="dblclickSelectObsers" rows="8"></vxe-textarea>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="菌落计数" field="strainCount" span="12" :item-render="{}" title-overflow>
                  <template #default="params">
                    <!--                    <span v-if='resultIsDisabled()'>{{params.data.strainCount ? params.data.strainCount : ''}}</span>-->
                    <!--                    <template v-else>-->
                    <VxePulldownSelectionWithNa style="width: 100%" :isChild="false"
                      :url="'/api/bac/bac-union-colo-count/findBacUnionColoCountList'" @confirmClick="SelectRowClick1"
                      :tableColumn="[
                        { type: 'seq', title: '#', width: '30px' },
                        { field: 'name', title: '名称' },
                        { field: 'code', title: '编码', width: '60' }
                      ]" :aimKeys="[{ aimKey: 'strainCount', rowKey: 'name' }]" :displayTexts="['strainCount']"
                      :displayTextObj="params.data.strainCount ? params.data.strainCount : ''" />
                    <!--                      </template>-->
                  </template>
                </vxe-form-item>
                <vxe-form-item title="比例" field="bacRate" span="12" :item-render="{}" title-overflow>
                  <template #title>
                    <span class="margin-lr-xs">比例</span>
                  </template>
                  <template #default="params">
                    <vxe-input v-model="params.data.bacRate" placeholder="请输入比例" type="float" min="0" max="1"
                      clearable></vxe-input>
                  </template>
                </vxe-form-item>
                <vxe-form-item title="生化实验" field="experiment" span="24" :item-render="{}" title-overflow>
                  <template #title>
                    <span class="margin-lr-xs">生化实验</span>
                  </template>
                  <template #default="params">
                    <vxe-textarea v-model="params.data.experiment" placeholder="双击选择生化实验"
                      @dblclick="experimentClick"></vxe-textarea>
                  </template>
                </vxe-form-item>

                <vxe-form-item title="是否危急值" field="isAlarm" span="5" :item-render="{}" title-overflow="title">
                  <template #default="params">
                    <el-switch v-model="params.data.isAlarm" inline-prompt active-text="是" inactive-text="否"></el-switch>
                    <!-- <vxe-switch v-model="params.data.isAlarm" inline-prompt open-label="是" close-label="否" open-value="1" close-value="0"></vxe-switch> -->
                  </template>
                </vxe-form-item>

                <vxe-form-item title="危急值描述" field="alarmText" span="19" :item-render="{}" title-overflow="ellipsis">
                  <template #default="params">
                    <!-- <vxe-textarea v-model="params.data.alarmText" placeholder="危急值描述" :autosize="{ minRows: 4, maxRows: 16 }" resize="vertical"  @focus="showTypeCodeDrawer(params.data,'alarmText')" class='alarmText'></vxe-textarea> -->
                    <VxeRemarkDictSelection v-enterNextInput :isChild="false" :tableColumn="[
                      { field: 'code', title: '编码', width: `60px` },
                      { field: 'name', title: '名称', minWidth: `80px` }
                    ]" :url="`/api/sys/basDictDetail/findDictDetailList`" :displayTextObj="params.data.alarmText"
                      @confirmClick="germAlarmConfirm" :dataObj="{ code: 'cultiObserAlarm' }"></VxeRemarkDictSelection>
                  </template>
                </vxe-form-item>

              </vxe-form>
            </div>
            <vxe-toolbar>
              <template #buttons>
                <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="下一步"
                  @click="addStainingMethodDialog(null)" :disabled='resultIsDisabled()'></vxe-button>
                <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="工作单"
                  :disabled='resultIsDisabled()' @click="reprintLabel"></vxe-button>
                <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="补打标签"
                  :disabled='resultIsDisabled()' @click="openDialog"></vxe-button>
                <el-dropdown trigger="click">
                  <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="继续培养"
                    split-button :disabled='resultIsDisabled()'>
                    继续培养
                    <el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </vxe-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-for="(item, index) in bacDescOptionList" :key="index"
                        @click="continuousCultivation(item)">
                        <span>{{ item.proResultNa }}</span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <vxe-button v-if="formData.bacPublishStatus === 0 || IsEmpty(formData.bacPublishStatus)" type="text"
                  class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="发布涂片报告" @click="publishSecReport"
                  :disabled='resultIsDisabled()'></vxe-button>
                <vxe-button v-if="formData.bacPublishStatus === 1" type="text" class="button-red margin-lr-xs"
                  class-name="margin-lr-xs" content="撤销涂片报告" @click="revokeSecReport"
                  :disabled='resultIsDisabled()'></vxe-button>
                <vxe-button type="text" class="button-blue margin-lr-xs" :content="'历史报告'"
                  @click="rptSecondReportHistory"></vxe-button>

                <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="预览"
                  @click="previewSecondRpt"></vxe-button>
                <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="打印"
                  @click="printSecondRpt"></vxe-button>

                <!-- <vxe-button type="text" class="button-blue margin-left-xs" transfer placement="bottom">
                  <template #default>打印</template>
                  <template #dropdowns>
                    <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="预览"
                      @click="previewSecondRpt"></vxe-button>
                    <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="打印"
                      @click="printSecondRpt"></vxe-button>
                  </template>
                </vxe-button> -->


                <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="镜检图"
                  @click="imageSelection" :disabled='resultIsDisabled()'></vxe-button>
              </template>
            </vxe-toolbar>
          </Pane>
          <Pane size="20">
            <el-scrollbar height="180px" class="padding-xs">
              <el-image v-for="(item, idx) in srcList" :key="idx" style="width: 100%; height: 100px"
                :src="combinePicPath(item)" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                :preview-src-list="previewSrcList" :initial-index="4" fit="cover" />
            </el-scrollbar>
          </Pane>
        </Splitpanes>
      </div>
    </div>
    <Splitpanes style="width: 100%; height: calc(100% - 430px)" v-show="activeName === 'second'" horizontal>
      <Pane size="50">
        <div style="height: calc(100%)">
          <vxe-table ref="bacDrugTestResultRef" height="auto" border show-overflow
            :header-cell-style="setBacDrugTestResultHeaderCellStyle" :data="stainingResultList"
            :row-config="{ isCurrent: true }" :column-config="{ resizable: true }"
            :edit-config="{ trigger: 'click', mode: 'cell', showIcon: false }" @current-change="stainingMethodCellClick"
            :expand-config="{ expandAll: true, reserve: true }" :tree-config="{
              expandAll: true,
              transform: true,
              rowField: 'id',
              parentField: 'parentId'
            }" :menu-config="tableMenu" @menu-click="contextMenuClickEvent" resizable keep-source
            @cell-dblclick="bacDrugTestRowClick" :cell-style="stainingResultCellColor">
            <vxe-column type="seq" width="30"></vxe-column>
            <vxe-column type="checkbox" width="30" align="center"></vxe-column>
            <vxe-column title="" width="30" align="left">
              <template #default="{ row }">
                <vxe-button v-if="row.handleType != 0" type="text" title="添加子级" status="primary"
                  icon="vxe-icon-square-plus" circle @click="addStainingMethodDialog(row.id)"></vxe-button>
              </template>
            </vxe-column>
            <vxe-column field="handleType" title="类型" width="100" tree-node>
              <template #default="{ row }">
                <span>{{ getIsStaticStatusDesc(row.handleType) }}</span>
              </template>
            </vxe-column>
            <vxe-column field="stainingMethNa" title="操作内容" min-width="120px">
              <template #default="{ row }">
                <span v-if="row.handleType == 0 && row.stainingConcOptNa">{{ row.stainingMethNa + row.stainingConcNa +
                  row.stainingConcOptNa }}</span>
                <span v-if="row.handleType == 0 && !row.stainingConcOptNa">{{ row.stainingMethNa }}</span>
                <span v-if="row.handleType == 0 && !row.stainingConcOptNa" style="color: blue">(双击弹窗编辑染色结果)</span>
                <span v-if="row.handleType == 0 && !row.stainingConcOptNa">{{ row.stainingConcNa }}</span>
                <span v-if="row.handleType == 1 || row.handleType == 2">{{ row.descText + (row.culMediumNa ? '，' +
                  row.culMediumNa : '') }}</span>
                <span v-if="row.handleType == 3">{{ row.descText }}</span>
              </template>
            </vxe-column>
            <vxe-column field="createTime" title="操作时间" width="130">
              <template #default="{ row }">
                <span>{{ row.createTime }}</span>
              </template>
            </vxe-column>
            <vxe-column field="userName" title="操作人" width="75" align="center"></vxe-column>
            <vxe-column field="isAlarm" title="危急值" width="75" align="center">
              <template #default="{ row }">
                <span v-if="row.isAlarm == 1" style="color: red">{{ `是` }}</span>
                <span v-else>{{ `否` }}</span>
              </template>
            </vxe-column>
            <!-- <vxe-column title="操作" fixed="right" width="80">
              <template #default="{ row }">
                <el-select v-model="row.handleType" placeholder="下拉选择">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" @click="selectChange(item)" />
                </el-select>
              </template>
            </vxe-column> -->
          </vxe-table>
        </div>
      </Pane>
      <Pane size="50">
        <BacHistories ref="BacHistoriesLeftRef" style="height: 100%" v-show="activeName === 'second'" />
      </Pane>
    </Splitpanes>

    <vxe-modal v-model="secReportDialog" title="发布二级报告" :mask="false" width="70vw" height="70vh" :destroy-on-close="true"
      show-zoom resize>
      <template #default>
        <BacSecReport ref="refBacSecReport"></BacSecReport>
        <div class="flex justify-end" style="margin-top: 20px">
          <vxe-button type="text" class="button-blue margin-left-xs" content="确定"
            @click="confirmSecReportV1"></vxe-button>
          <vxe-button type="text" class="button-white margin-left-xs" content="取消"
            @click="secReportDialog = false"></vxe-button>
        </div>
      </template>
    </vxe-modal>

    <vxe-modal v-model="stainResultDialog" title="染色结果" :mask="false" width="40vw" height="25vh" :destroy-on-close="true"
      show-zoom resize>
      <template #title>
        <span>选择染色结果</span>
      </template>
      <template #default>
        <vxe-form title-width="90" :data="currentStainResult" title-align="right" span="23">
          <vxe-form-item title="染色方法" field="iqcMaterialId">
            <template #default="{ data }">
              <vxe-input v-model="data.stainingMethNa" disabled></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item title="染色结果" field="iqcMaterialId">
            <template #default="{ data }">
              <vxe-select v-model="data.stainingConcOptNo" transfer>
                <vxe-option v-for="item in stainOptions" :key="item.resultCode" :value="item.resultCode"
                  :label="item.resultName"></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item title=" " field="isAlarm">
            <template #default="{ data }">
              <vxe-checkbox v-model="data.isAlarm" content="危急值" :checked-value="1" :unchecked-value="0"
                @change="criValueChange"></vxe-checkbox>
              <span class="margin-lr">&nbsp;</span>
              <vxe-checkbox v-model="currentStainResult.isPushSecReport" content="发布二级报告" :checked-value="1"
                :unchecked-value="0"></vxe-checkbox>
            </template>
          </vxe-form-item>
          <vxe-form-item align="right">
            <vxe-button status="primary" @click="saveCurrentStainResult">确定</vxe-button>
          </vxe-form-item>
        </vxe-form>
      </template>
    </vxe-modal>

    <BacProcessRecords ref="BacProcessRecordsRef" v-show="activeName === 'third'" :businessType="'node2'" />
    <Cost ref="costRef" v-show="activeName === 'fifth'" style="height: calc(100% - 39px - 33px)" />
    <!-- 设置菌落形态 -->
    <BacObserSelection ref="BacObserSelectionRef" @obserConfirm="obserConfirm" />
    <BacObserBatch ref="BacObserBatchRef" @refresh="refresh"/>
    <!-- 染色结果选择 -->
    <BacStainingSelection ref="BacStainingSelectionRef" />

    <el-dialog title="染色方法" :show-close="false" v-model="showDialog" width="90vw" :close-on-click-modal="false"
      destroy-on-close v-if="showDialog" class="dyeingMethodDialog">
      <div class="dyeingMethodBodyDialog">
        <div class="dialogHeader">
          <div class="headerTitle">培养基</div>
          <div class="headerRadioGroup" v-if="bacCultureCombinationList.length > 0">
            <el-radio-group v-model="radioValue">
              <el-radio :label="val.id" :value="val.id" v-for="(val, i) in bacCultureCombinationList" :key="i">{{
                val.cultrueNa }}</el-radio>
            </el-radio-group>
          </div>
          <el-divider />
        </div>
        <div class="dialogBody">
          <div class="bodyRadioGroup">
            <el-radio-group v-model="radio1" @change="radioChange">
              <el-radio :label="'0'">涂片</el-radio>
              <el-radio :label="'2'">转种</el-radio>
              <el-radio :label="'1'">分纯</el-radio>
            </el-radio-group>
          </div>
          <div class="tablesDiv">
            <Splitpanes class="area" v-if="boolFlag">
              <Pane size="35">
                <vxe-table ref="methodTableRef" border align="left" class="mytable-scrollbar" resizable :loading="loading"
                  height="auto" :data="methodTableData" :edit-config="{ trigger: 'click', mode: 'cell' }"
                  :row-config="{ isCurrent: true }" :column-config="{ resizable: true }" show-overflow keep-source
                  :scroll-y="{ enabled: true }" @current-change="methodTableCellClick">
                  <vxe-column type="checkbox" width="26"></vxe-column>
                  <vxe-column type="seq" title="#" width="30"></vxe-column>
                  <vxe-column field="methodCode" title="编号"></vxe-column>
                  <vxe-column field="methodName" title="染色方法"></vxe-column>
                  <vxe-column field="description" title="描述"></vxe-column>
                  <vxe-column field="inputCode" title="助记符"></vxe-column>
                </vxe-table>
              </Pane>
              <Pane size="65">
                <vxe-table ref="conclusionTableRef" border align="left" class="mytable-scrollbar" resizable
                  :edit-config="{ trigger: 'click', mode: 'cell' }" :loading="loading" height="auto"
                  :data="conclusionTableData" :row-config="{ isCurrent: true }" :column-config="{ resizable: true }"
                  show-overflow keep-source :scroll-y="{ enabled: true }" @checkbox-change="onConclusionCheckboxChange">
                  <vxe-column type="checkbox" width="26" @checkbox-change="onConclusionCheckboxChange"></vxe-column>
                  <vxe-column type="seq" title="#" width="30"></vxe-column>
                  <vxe-column field="conclusionCode" title="编号"></vxe-column>
                  <vxe-column field="conclusionName" title="染色结论"></vxe-column>
                  <vxe-column field="clinicalSignificance" title="临床意义"></vxe-column>
                  <vxe-column field="inputCode" title="助记符"></vxe-column>
                </vxe-table>
              </Pane>
            </Splitpanes>
            <Splitpanes class="area1" v-else>
              <Pane>
                <vxe-table ref="cultureCombinationRef" border align="left" class="mytable-scrollbar" resizable
                  height="auto" :loading="loading" :data="cultureCombinationData"
                  :edit-config="{ trigger: 'click', mode: 'cell' }" :row-config="{ isCurrent: true }"
                  :column-config="{ resizable: true }" show-overflow keep-source :scroll-y="{ enabled: true }">
                  <vxe-column type="checkbox" width="26"></vxe-column>
                  <vxe-column type="seq" title="#" width="30"></vxe-column>
                  <vxe-column field="code" title="培养基组合编码"></vxe-column>
                  <vxe-column field="name" title="培养基组合名称"></vxe-column>
                  <vxe-column field="inputCode" title="助记符"></vxe-column>
                </vxe-table>
              </Pane>
            </Splitpanes>
          </div>
          <div class="dialog-footer flex right justify-end" style="margin: 10px 0 10px 0">
            <el-button type="primary" @click="saveBacthStaining()">确定</el-button>
            <el-button @click="closeDialog()">取消</el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <el-dialog title="培养基" :show-close="false" v-model="dialog" append-to-body width="1000px"
      :close-on-click-modal="false">
      <!-- <vxe-toolbar perfect>
        <template #buttons>
          <vxe-button type="text" class="button-blue" content="查询" :loading="lloading" @click="getCultureDetail"></vxe-button>
        </template>
      </vxe-toolbar> -->
      <div class="tableBody">
        <vxe-table ref="cultureTableRef" class="mytable-scrollbar" border="inner" align="left" height="500"
          :data="cultureTableList" :loading="lloading" :column-config="{ resizable: true }" resizable show-overflow
          keep-source>
          <vxe-column type="checkbox" width="30px" align="center"></vxe-column>
          <vxe-column type="seq" title="序号" width="30"></vxe-column>
          <vxe-column field="sampleNo" title="标本号" align="center"></vxe-column>
          <vxe-column field="reqNo" title="条码号" align="center"></vxe-column>
          <vxe-column field="cultureNo" title="编号" align="center"></vxe-column>
          <vxe-column field="cultureNa" title="名称"></vxe-column>
        </vxe-table>
      </div>
      <div class="dialog-footer flex right justify-end" style="margin-top: 10px;">
        <el-button type="primary" @click="printLabel">确定</el-button>
        <el-button @click="closeDialog()">取消</el-button>
      </div>
    </el-dialog>


    <el-dialog title="生化实验" :show-close="false" v-model="exDialog" append-to-body width="1000px"
      :close-on-click-modal="false">
      <div class="tableBody">
        <vxe-table ref="exTableRef" class="mytable-scrollbar" border="inner" align="left" height="500" :data="exTableList"
          :loading="exloading" :column-config="{ resizable: true }" resizable show-overflow keep-source>
          <vxe-column type='checkbox' width='26'></vxe-column>
          <vxe-column type='seq' title='#' width='30'></vxe-column>
          <vxe-column field='code' title='编号' align="center"> </vxe-column>
          <vxe-column field='name' title='名称' align="center"> </vxe-column>
          <vxe-column field='inputCode' title='助记符' align="center"> </vxe-column>
        </vxe-table>
      </div>
      <div class="dialog-footer flex right justify-end" style="margin-top: 10px;">
        <el-button type="primary" @click="confirm">确定</el-button>
        <el-button @click="closeExDialog()">取消</el-button>
      </div>
    </el-dialog>

    <!-- 静默打印 -->
    <QuietPrint ref="quietPrintRef" :printParams="printParamsObj" />
    <!-- 发布二级报告 授权验证 -->
    <AuthValidateComp ref="AuthValidateCompRef" @unChkConfirm="validatePermisionFinish" />
    <!-- 镜检截图 -->
    <BacCultiObserImageResult ref="BacCultiObserImageResultRef" @SelectedCallback="imgSelectedCallback"
      @loadImgsCallback="loadImgsCallback" />
    <!-- 危机值上报 -->
    <BacCriticalObserReport ref="criticalObserReportRef" @treatFinish="alarmTreatFinish" />
    <!-- 二级报告发布历史 -->
    <BacSecondReportHistory ref="BacSecondReportHistoryRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, getCurrentInstance, defineProps, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { formatDateTime, IsEmpty } from '@/utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import BacHistories from './BacHistories.vue';
import BacObserSelection from './BacObserSelection.vue'; /**菌落形态结果选择 */
import BacObserBatch from './BacObserBatch.vue'; /**菌落形态结果选择 */
import BacStainingSelection from './BacStainingSelection.vue'; /**染色结果选择 */
import BacProcessRecords from './BacProcessRecords.vue'; /**流程记录 */
import SelectDataGrid from '@/components/SelectDataGrid.vue';
import QuietPrint from '@/components/QuietPrint.vue'; /**静默打印组件 */
import Cost from './Cost.vue';
import VxePulldownSelectionWithNa from '@/components/VxePulldownSelectionWithNa.vue';
import BacSecReport from './BacSecReport.vue';
import AuthValidateComp from '@/components/AuthValidateComp.vue';
import BacCultiObserImageResult from './BacCultiObserImageResult.vue';
import BacCriticalObserReport from '@/views/lab_sys/bac_bus/components/BacCriticalObserReport.vue'; //危急值上报
import VxeRemarkDictSelection from '@/components/VxeRemarkDictSelection.vue';
import { VXETable, VxeTableInstance } from 'vxe-table';
import BacSecondReportHistory from './BacSecondReportHistory.vue';
import { GetGolbalOptions, GetRptGroupOptions, GetRptGroupOptionsAsync } from '@/utils/SysOptionsHelper';
import { getOptionValueByCodeRptGroupOption, getOptionValueByCodeGlobalOption } from '@/utils/SysOptionsHelper';
// 页面加载时更新报告单元/字典
onMounted(async () => {
  getDictItemsList(); //批量获取字典
});
defineExpose({
  initPage,
  initTestList,
  drugResultTempLdateQuickInsert /**药敏模板快速输入 */,
  imgSelectedCallback /**重新刷新选中图列表 */,
  cultureSubcultivation,
  autoPrintLabel
});
//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['obserResult'];

  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });

  const iosObj = dictTreeTypeItems.data.find((item: any) => item.code === 'obserResult');
  obserResultList.push(...iosObj.detailDataList);
}
let exTableList: any = reactive([]); //弹出框List
let exloading = ref(false); //加载状态
let exDialog = ref(false);

let cultureTableList: any = reactive([]); //弹出框List
let lloading = ref(false); //加载状态


let radioValue = ref('');
let radio1 = ref('0');

const value = ref('');

const options = [
  {
    value: '0',
    label: '涂片'
  },
  {
    value: '2',
    label: '转种'
  },
  {
    value: '1',
    label: '分纯'
  }
];
let loadingAdd = ref(false);
const methodId: any = ref(null);
const srcList = reactive([]);
const previewSrcList = reactive([]);
let printParamsObj = ref(null); /**静默打印参数 */
let boolFlag = ref(true);
let { proxy }: any = getCurrentInstance();
const rptCultiObserResultRef = ref(null); /**细菌结果列表对象 */
const bacDrugTestResultRef = ref(null); /**药敏结果列表对象 */
const formObserRef: any = ref(null); /**菌落形态观察结果表单对象 */
const BacObserSelectionRef = ref(null); /**设置菌落形态弹窗选择对象 */
const BacObserBatchRef = ref(null); /**设置菌落形态弹窗选择对象 */
const BacHistoriesLeftRef = ref(null); /**历史回顾 */
const BacStainingSelectionRef = ref(); /**菌落形态弹窗选择 */
const BacProcessRecordsRef = ref(null); /**过程记录对象 */
const AuthValidateCompRef = ref(null); /**发布二级报告 授权验证 */
let refBacSecReport = ref(null);
let showDialog = ref(false); //添加弹框展示状态
let dialog = ref(false); //添加弹框展示状态
let secReportDialog = ref(false);
let stainResultDialog = ref(false);
let stainingResultList: any = reactive([]); //染色方法数据
let currentStainResult: any = reactive({});
let methodTableData: any = reactive([]); //弹框染色方法
let cultureCombinationData: any = reactive([]); //弹框培养基组合
let conclusionTableData: any = reactive([]); //弹框表格数据
const methodTableRef = ref(null); /**表格ref标记*/
const conclusionTableRef = ref(null); /**表格ref标记*/
const criticalObserReportRef = ref(null);/**危急值上报 */
let bacActive = ref(0); /**当前选中第几珠菌 */
let formData: any = reactive({ id: '', morphologyName: '', strainCount: '', bacRate: 0, experiment: '' }); /**菌落形态观察结果表单 */
let labMainInfoObj: any = reactive({}); /**检验记录当前选中对象 */
let stepNodeObj: any = reactive({}); /**当前选中流程节点对象 */
let sltWorkFlowObj: any = reactive({}); /**当前选中流程节点对象 */
const loading = ref(false); /**刷新+表格加载*/
let currentRow: any = reactive({ id: '', code: '' });
let strainCurrentRow: any = reactive({}); //菌株
let stainingMethodRow: any = reactive([]); //染色结果
let form: any = reactive({
  autocalc: false
});
let activeName = ref('second');
let transResultList: any = reactive([]); //模版表格数据
let obserResultList: any = reactive([]); //模版表格数据
const transResultRef = ref<VxeTableInstance<RowVO>>(); //表格ref标记
let bacCultiObserList: any[] = reactive([]); /**细菌菌株 */
let bacDescOptionList: any[] = reactive([]); /**继续培养 */
let stainOptions = reactive([]);
let strainingPanelHeight = ref(50); /**染色结果列表高度 */
let bacCultureCombinationList: any[] = reactive([]); /**培养基 */
let reportId = ref(''); //报表id
let bacCultureCombinaRelList: any[] = reactive([]); /**培养基和培养基组合中间表 */
let costRef: any = ref(null); //费用传值
let isReportAlarm = ref(false); /**染色结果是否发布危急值 */
const BacCultiObserImageResultRef = ref(null); /**镜检截图组件对象 */
const BacSecondReportHistoryRef = ref(null);/* 二级报告发布界面 */
let secReportMustSelectStaing = ref('');/* 二级报告必须选择染色方法 */
let tableMenu = {
  className: 'my-menus',
  body: {
    options: [[{ code: 'remove', name: '删除', prefixIcon: 'vxe-icon-delete color-red' }]]
  }
};

let quietPrintRef: any = ref<InstanceType<typeof quietPrintRef>>();

function contextMenuClickEvent({ menu, row, column }) {
  const url = '/api/bac/bac-staining-result/deleteBacStainingResult';
  proxy.$http
    .post(url, row)
    .then((res: any) => {
      VxeMessage(res.status.msg, VxeNotifyType.success);
      findStainingResult(strainCurrentRow); // 刷新结果表格
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

/**初始化界面 */
function initPage(mainInfoRow: any, stepNode: any, sltWorkFlow: any) {
  const a = getOptionValueByCodeRptGroupOption('wswfbejbgbxxzrsgc');
  secReportMustSelectStaing.value = a;
  Object.assign(labMainInfoObj, mainInfoRow);
  Object.assign(stepNodeObj, stepNode);
  Object.assign(sltWorkFlowObj, sltWorkFlow);
  findRptCultiObserResult('1');
  findBacDescOptionList();
  findCultureInfo();
  getReportId();
  getBacHistories();
  getObserResultList();
  //fixme:20241206临时放在这里,粗暴的解决打开组件无图片的问题
  //imgSelectedCallback();
}

function tabHandleClick(tab: { paneName: string; }) {
  if (tab.paneName === 'third') {
    BacProcessRecordsRef.value?.initRecords(labMainInfoObj, stepNodeObj);
  } else if (tab.paneName === 'fifth') {
    costRef.value.getreqDetail(labMainInfoObj);
  }
}

//血培养转种
function cultureSubcultivation(row: any) {
  console.log('血培养转种', row);
}

// 点击表格当前行
async function bacDrugTestRowClick({ row, $event, column }) {
  stainOptions.length = 0;
  if (row.handleType == 0 && column.field == 'stainingMethNa') {
    const url = '/bac/staining/options/findStainingOptionsList';
    let data = { stainingConclusionId: row.staConclusionNo } as any;
    await proxy.$http
      .get(url, { params: data })
      .then((res: any) => {
        if (res && res.data && res.data.length >= 0) {
          stainOptions = res.data;
        }
      })
      .catch((err: any) => { });
    Object.assign(currentStainResult, row);
    stainResultDialog.value = true;
  }
}

/**发布二级报告验证授权完成 */
function validatePermisionFinish(e: any) {
  saveCurrentStainResult({}, true);
}

function saveCurrentStainResult({ }, iscallback = false) {
  if (iscallback === false && currentStainResult.isPushSecReport === 1) {
    AuthValidateCompRef.value?.initPage('3');
    return;
  }

  const data: any = stainOptions.filter((a) => a.resultCode == currentStainResult.stainingConcOptNo);
  const bacStainingResult = {};
  Object.assign(bacStainingResult, currentStainResult);
  // const aa = {
  //   id: stainingResultTableDate.id,
  //   stainingConcOptNo: data[0].resultCode,
  //   stainingConcOptNa: data[0].resultName,
  //   stainingOptionsId: data[0].id,
  //   isAlarm: currentStainResult.isAlarm
  // };

  bacStainingResult.stainingConcOptNo = data[0].resultCode;
  bacStainingResult.stainingConcOptNa = data[0].resultName;
  bacStainingResult.stainingOptionsId = data[0].resultName;
  bacStainingResult.stainingOptionsId = data[0].id;
  //修改列表数据不刷新
  const result = stainingResultList.filter((p: { id: any; }) => p.id == currentStainResult.id);
  result[0].stainingConcOptNa = data[0].resultName;
  result[0].stainingConcOptNo = data[0].resultCode;
  result[0].isAlarm = currentStainResult.isAlarm;
  result[0].isPushSecReport = currentStainResult.isPushSecReport;
  const url = '/api/bac/bac-staining-result/updateBacStainingResult';
  proxy.$http
    /**注意此处的数据条数*/
    .post(url, bacStainingResult)
    .then(async (res: any) => {
      // findStainingResult(strainCurrentRow);
      // courseRecord(`修改${e.resultName}结果`);
      VxeMessage('添加结果成功', VxeNotifyType.success);

      stainResultDialog.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取染色结果列表数据异常', VxeNotifyType.error);
    });
}

//继续培养
function findBacDescOptionList() {
  bacDescOptionList.length = 0;
  if (IsEmpty(labMainInfoObj.id)) {
    return;
  }
  const url = '/bac-cul-pro-result/findBacDescOptionList';
  let data = { searchValue: '' } as any;
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      if (res && res.data && res.data.length >= 0) {
        Object.assign(bacDescOptionList, res.data);
      }
    })
    .catch((err: any) => { });
}

//根据父组件传过来的培养基组合ID获取所有培养基
function findBacCultureMediumList() {
  const cultureCombinationList: any[] = [];
  if (IsEmpty(sltWorkFlowObj._value.cultureCombinationIds)) {
    return;
  }
  const url = '/api/bac/bac-cultrue-combination/findBacCultureCombinationListByIds';
  proxy.$http
    .get(url, { params: { ids: sltWorkFlowObj._value.cultureCombinationIds && sltWorkFlowObj._value.cultureCombinationIds.length > 0 ? sltWorkFlowObj._value.cultureCombinationIds : [] } })
    .then((res: any) => {
      if (res && res.data && res.data.length >= 0) {
        cultureCombinationList.push(...res.data);
        for (const irow of cultureCombinationList) {
          bacCultureCombinationList.push({
            cultrueId: irow.code,
            cultrueNa: irow.name,
            id: irow.code
          });
        }
      }
    })
    .catch((err: any) => { });
}

//查询当前标本下的培养基
function findCultureInfo() {
  bacCultureCombinationList.length = 0;
  const url = '/api/bac/bac-culture-medium/findBacCultureMediums';
  // let data = { searchValue: '' } as any;
  proxy.$http
    .get(url, { params: { maininfoId: labMainInfoObj.id, rptGroup: labMainInfoObj.rptGroup, sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'), sampleNo: labMainInfoObj.sampleNo } })
    .then((res: any) => {
      if (res && res.data) {
        //&& res.data.length >= 0
        //bacCultureCombinationList.push(res.data)
        //Object.assign(bacCultureCombinationList, res.data);
        for (const irow of res.data) {
          bacCultureCombinationList.push({
            cultrueId: irow.code,
            cultrueNa: irow.name,
            id: irow.code
          });
        }
        // findBacCultureMediumList();
      }
    })
    .catch((err: any) => { });
}

// 接收父组件传值
function initTestList(repData: any, isCbUptMainInfo = true) {
  if (IsEmpty(repData) || !repData) {
    //resultList.length = 0;
    return;
  }
  Object.assign(labMainInfoObj, repData);
  findRptCultiObserResult('1');
}

/**查询菌株 */
function findRptCultiObserResult(a: string) {
  bacCultiObserList.length = 0;
  if (IsEmpty(labMainInfoObj.id)) {
    return;
  }
  const url = '/bac/strain/findStrain';
  let data = { mainInfoId: labMainInfoObj.id, rptGroup: labMainInfoObj.rptGroup, sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'), sampleNo: labMainInfoObj.sampleNo } as any;
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      if (res && res.data && res.data.length >= 0) {
        Object.assign(bacCultiObserList, res.data);
        //rptCultiObserResultRef.value?.setCurrentRow(res.data[0]);
        if (bacCultiObserList.length > 0) {
          if (a === '1') {
            bacCultiObserItemClick(bacCultiObserList[0]);
            //findStainingResult(bacCultiObserList[0]);
          } else {
            bacCultiObserItemClick(bacCultiObserList[bacCultiObserList.length - 1]);
            //findStainingResult(bacCultiObserList[bacCultiObserList.length - 1]);
          }
        }
      }
      loadingAdd.value = false;
    })
    .catch((err: any) => { });
}
//上一个
function prevCLick() {
  actionCLick({ event: 'prevCode' });
}
//下一个
function nextCLick() {
  actionCLick({ event: 'nextCode' });
}

function actionCLick(item: { event: string; }) {
  proxy.$emit('actionBtnsClick', item);
}

function addCulResult() {
  const $table = proxy.$refs.transResultRef as any;
  const newRec = {
    obserResult: '',
    rptGroup: labMainInfoObj.rptGroup,
    sampleda: labMainInfoObj.sampleda,
    sampleNo: labMainInfoObj.sampleNo,
    testFlowNo: stepNodeObj.testFlowNo,
    testNodeNo: stepNodeObj.nodeNo,
  } as any;

  transResultList.push(newRec);
  $table.reloadData(transResultList);
  $table.setEditRow(newRec);
  proxy.$nextTick(() => {
    setTimeout(() => {
      $table.scrollToRow(newRec);
    }, 50);
  });
}

//添加菌株
function addStrain() {
  loadingAdd.value = true;
  const row = {
    id: '',
    strainCode: bacCultiObserList.length + 1,
    strainName: `第${bacCultiObserList.length + 1}株菌`,
    rptGroup: labMainInfoObj.rptGroup,
    sampleda: labMainInfoObj.sampleda,
    sampleNo: labMainInfoObj.sampleNo,
    maininfoId: labMainInfoObj.id,
    workFlowId: stepNodeObj.workFlowId,
    workFlowNodeId: stepNodeObj.workFlowNodeId,
    testFlowNo: stepNodeObj.testFlowNo,
    testNodeNo: stepNodeObj.nodeNo
  };

  const url = '/bac/strain/addStrain';
  proxy.$http
    .post(url, row)
    .then((res: any) => {
      /*  courseRecord('新增菌株');*/
    })
    .catch((err: any) => {
      loadingAdd.value = false;
      VxeMessage('新增失败', VxeNotifyType.success);
    });
  setTimeout(() => {
    findRptCultiObserResult('0');
  }, 500);
}
//批量新增
function addStrainBatch() {
  let data={
    count: bacCultiObserList.length,
    rptGroup: labMainInfoObj.rptGroup,
    sampleda: labMainInfoObj.sampleda,
    sampleNo: labMainInfoObj.sampleNo,
    maininfoId: labMainInfoObj.id,
    testFlowNo: stepNodeObj.testFlowNo,
    testNodeNo: stepNodeObj.nodeNo
  }
  BacObserBatchRef.value?.showModal(data);
}
/* 删除菌株 */
async function deleteStrain() {
  const type = await VXETable.modal.confirm('确定删除选中的菌株？');
  if (type === 'confirm') {
    const url = '/bac/strain/deleteStrain';
    proxy.$http
      .post(url, strainCurrentRow)
      .then((res: any) => {
        findRptCultiObserResult('0');
        if (res && res.status && res.status.code === 1) {
          /* try {
             courseRecord(`删除【第${strainCurrentRow.strainCode}珠菌】`);
           } catch (error) { }*/
        }
      })
      .catch((err: any) => {
        VxeMessage('删除失败', VxeNotifyType.success);
      });
  }
}
function save() {
  if (IsEmpty(strainCurrentRow.strainCode)) {
    VxeMessage('请选择菌株', VxeNotifyType.error);
    return;
  }
  if (labMainInfoObj.id && strainCurrentRow.id) {
    const data = {
      id: formData.id,
      maininfoId: labMainInfoObj.id,
      wkFlwId: stepNodeObj.workFlowId,
      wkFlwNodeId: stepNodeObj.workFlowNodeId,
      isolateNum: strainCurrentRow.strainCode,
      morphologyName: formData.morphologyName,
      strainCount: formData.strainCount,
      bacRate: formData.bacRate,
      experiment: formData.experiment,
      sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
      rptGroup: labMainInfoObj.rptGroup,
      sampleNo: labMainInfoObj.sampleNo,
      testFlowNo: stepNodeObj.testFlowNo,
      testNodeNo: stepNodeObj.nodeNo,
      isAlarm: formData.isAlarm,
      alarmText: formData.alarmText
    };
    const url = '/api/bac/bac-obser-result/saveOrUpdateBacObserResult';
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        if (res && res.status && res.status.code === 1) {
          Object.assign(formData, res.data);

          proxy.$emit('currentRow', labMainInfoObj);
          /*    try {
                const a = localStorage.getItem('userInfo');
                const b = JSON.parse(a);
                const contentSrr = [
                  `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】保存【第${strainCurrentRow.strainCode}珠菌】菌株观察\n`,
                  !IsEmpty(formData.morphologyName) ? '结果描述: ' + formData.morphologyName + '' : '',
                  !IsEmpty(formData.strainCount) ? '菌落计数: ' + formData.strainCount + '' : '',
                  !IsEmpty(formData.experiment) ? '生化实验: ' + formData.experiment + '' : '',
                  !IsEmpty(formData.isAlarm) ? '危急值: ' + (formData.isAlarm ? '是' : '否') + '' : '',
                  !IsEmpty(formData.alarmText) ? '危急值描述:' + formData.alarmText + '' : '',
                  !IsEmpty(formData.bacRate) ? '菌群比例:' + formData.bacRate + '' : '',
                ].filter(Boolean).join('\n');
                courseRecord(`${contentSrr}`);
              } catch (err) { }*/
        }
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });

  }
}
function getObserResultList() {
  transResultList.length = 0;
  let data = {
    rptGroup: labMainInfoObj.rptGroup,
    sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
    sampleNo: labMainInfoObj.sampleNo,
    testFlowNo: stepNodeObj.testFlowNo,
    testNodeNo: stepNodeObj.nodeNo
  };
  formData.morphologyName = '';
  const url = '/api/bac/obserResultNoGerm/getObserResultList';
  proxy.$http
    /**注意此处的数据条数*/
    .get(url, { params: data })
    .then(async (res: any) => {
      transResultList.push(...res.data);
    })
    .catch((err: any) => {
      VxeMessage('获取细菌结果异常', VxeNotifyType.error);
    });
}
function saveCulResult() {
  if (transResultList.length > 0) {
    const url = '/api/bac/obserResultNoGerm/saveOrUpdate';
    proxy.$http
      .post(url, transResultList)
      .then((res: any) => {
        VxeMessage('修改成功', VxeNotifyType.success);
        getObserResultList();
        setTimeout(() => {
          //findTextResult();
        }, 500);
      })
      .catch((err: any) => {
        VxeMessage('修改失败', VxeNotifyType.success);
      });
  } else {
    VxeMessage('无添加或修改数据', VxeNotifyType.error);
  }
}
function handleDelete() {
  const arr = transResultRef.value?.getCheckboxRecords(true);
  // const sltTemplates = (proxy.$refs.templateTableRef as any).getCheckboxRecords();
  if (!(arr && arr.length > 0 && arr[0])) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const url = '/api/bac/obserResultNoGerm/batchDelete';
        proxy.$http
          .post(url, arr)
          .then((res: any) => {
            VxeMessage(res.status.msg, VxeNotifyType.success);
            getObserResultList();
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  }
}
let leftCurrentRow = reactive({}); //左侧表格选中的当前行
function findStainingMethod() {
  loading.value = true;
  methodTableData.length = 0; /**放入数据前清空数据*/
  const url = '/bac/staining/method/findStainingMethodList';
  proxy.$http
    /**注意此处的数据条数*/
    .get(url, { keyWords: form.keyvalue })
    .then(async (res: any) => {
      methodTableData.push(...res.data);
      loading.value = false;
      if (res && res.data && res.data.length > 0) {
        const newSelRow = res.data[0];
        leftCurrentRow = newSelRow;
        methodTableCellClick({ row: newSelRow });
        const $table = methodTableRef.value;
        if ($table) {
          await $table.setCurrentRow(newSelRow);
        }
      }
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取染色方法列表数据异常', VxeNotifyType.error);
    });
}

//获取分纯,转种数据
function findCultureCombination() {
  loading.value = true;
  cultureCombinationData.length = 0; /**放入数据前清空数据*/
  const url = '/api/bac/bac-cultrue-combination/findBacCultureCombinationListByType';
  const a = {
    type: radio1.value
  };
  proxy.$http
    .get(url, { params: a })
    .then(async (res: any) => {
      cultureCombinationData.push(...res.data);
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取染色方法列表数据异常', VxeNotifyType.error);
    });
}

/**表格选中当前行*/
function methodTableCellClick({ row }) {
  //BacStainingConclusionRef.value?.tempSelectChange(row);
  Object.assign(currentRow, row);
  leftCurrentRow = row;
  findStainingConclusionList(currentRow);
  proxy.$forceUpdate();
}

function findStainingConclusionList(row: { methodCode: any; }) {
  loading.value = true;
  conclusionTableData.length = 0; /**放入数据前清空数据*/
  const url = '/bac/staining/conclusion/findStainingConclusionList';
  /**注意此处的数据条数*/
  const a = {
    keyWords: form.keyvalue,
    stainingMethodId: row.methodCode
  };
  proxy.$http
    .get(url, { params: a })
    .then(async (res: any) => {
      conclusionTableData.push(...res.data);
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取染色结论列表数据异常', VxeNotifyType.error);
    });
}

/**设置表头单元格样式 */
function setBacDrugTestResultHeaderCellStyle({ column }) {
  if (column.field === 'r' || column.field === 'i' || column.field === 'sdd' || column.field === 's' || column.field === 'ecoff' || column.field === 'whonetTest' || column.field === 'breakPointRef' || column.field === 'guideline' || column.field === 'year' || column.field === 'germCodeType' || column.field === 'orgCodeType' || column.field === 'germNo' || column.field === 'breakPointType' || column.field === 'host' || column.field === 'infeSite' || column.field === 'refTable' || column.field === 'refTableSeq' || column.field === 'breakPointId') {
    return { fontWeight: 300 };
  }
}

/**药敏模板快速输入 */
function drugResultTempLdateQuickInsert(rows: any) {
  const curTestResultObj = rptCultiObserResultRef.value?.getCurrentRecord();
  let url = `/api/bac/bac-drug-test-result/drugResultTemplateQuickInsert`;
  proxy.$http
    .post(url, { mainInfoId: labMainInfoObj.id, rptCultiObserResultId: curTestResultObj.id, bacDrugResultTemplates: rows })
    .then(async (res: any) => {
      if (res && res.status && !IsEmpty(res.status.code) && res.status.code === 1) {
        //findBacDrugTestResult(curTestResultObj);
        VxeMessage(res.status.msg, VxeNotifyType.success);
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('删除失败', VxeNotifyType.error);
    });
}

/**菌株点击事件 */
function bacCultiObserItemClick(m: { id: any; }) {
  Object.assign(strainCurrentRow, m);
  bacCultiObserList.forEach((e, i) => {
    if (e.id === m.id) {
      e.isActive = true;
    } else {
      e.isActive = false;
    }
  });
  formData.id = '';
  formData.morphologyName = '';
  formData.strainCount = '';
  formData.bacRate = '';
  formData.experiment = '';
  formData.isAlarm = false;
  formData.alarmText = '';
  findStainingResult(m);
  findBacOvserResult(m);

  /**查询选中的镜检截图 */
  imgSelectedCallback();
}

/**双击选择菌落形态 */
function dblclickSelectObsers() {
  BacObserSelectionRef.value?.showModal(formData.morphologyName);
}
/**菌落形态确认选中 */
function obserConfirm(e: { cultureMedium: any; description: any; morphology: any; }) {
  if (!strainCurrentRow || IsEmpty(strainCurrentRow.strainCode)) {
    proxy.$alert("请先新增【菌株】", "提示");
    return;
  }
  let data = '';
  if (IsEmpty(e.cultureMedium)) {
    data = `${e.description} ${e.morphology}`;//e.cultureMedium + '(' + e.morphology + ')';
  } else {
    data = `${e.cultureMedium}: ${e.description} ${e.morphology}`;//e.cultureMedium + '(' + e.morphology + ')';
  }

  if (!IsEmpty(formData.morphologyName)) {
    formData.morphologyName = formData.morphologyName + '\n' + data;
  } else {
    formData.morphologyName = data;
  }
  if (labMainInfoObj.id && stepNodeObj.testFlowNo && stepNodeObj.nodeNo && strainCurrentRow.id) {
    const data = {
      id: formData.id,
      maininfoId: labMainInfoObj.id,
      wkFlwId: stepNodeObj.workFlowId,
      wkFlwNodeId: stepNodeObj.workFlowNodeId,
      isolateNum: strainCurrentRow.strainCode,
      morphologyName: formData.morphologyName,
      cultureMedium: e.cultureMedium,
      morphology: e.morphology,
      sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
      rptGroup: labMainInfoObj.rptGroup,
      sampleNo: labMainInfoObj.sampleNo,
      testFlowNo: stepNodeObj.testFlowNo,
      isAlarm: formData.isAlarm,
      testNodeNo: stepNodeObj.nodeNo
    };
    const url = '/api/bac/bac-obser-result/saveOrUpdateBacObserResult';
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        if (res && res.status && res.status.code == 1) {
          //Object.assign(formData, res.data);
          bacCultiObserItemClick(strainCurrentRow);
        }
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  }
}
function refresh(){
  findRptCultiObserResult('0');
}

// 添加染色方法
function addStainingMethodDialog(id: any) {
  if (IsEmpty(strainCurrentRow.strainCode)) {
    VxeMessage('请选择菌株', VxeNotifyType.error);
    return;
  }
  methodId.value = id;
  findCultureInfo();
  if (radio1.value == '0') {
    boolFlag.value = true;
    findStainingMethod();
  } else {
    boolFlag.value = false;
    findCultureCombination();
  }
  showDialog.value = true;
}

//继续培养
function continuousCultivation(item: { proResultNa: any; }) {
  if (IsEmpty(strainCurrentRow.strainCode)) {
    VxeMessage('请选择菌株', VxeNotifyType.error);
    return;
  }
  const bacStainingResultList = [];
  const addQcItem = {
    sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
    rptGroup: labMainInfoObj.rptGroup,
    sampleNo: labMainInfoObj.sampleNo,
    maininfoId: labMainInfoObj.id,
    wkFlwId: stepNodeObj.workFlowId,
    testFlowNo: stepNodeObj.testFlowNo,
    wkFlwNodeId: stepNodeObj.workFlowNodeId,
    testNodeNo: stepNodeObj.nodeNo,
    strainId: strainCurrentRow.id,
    strainNo: strainCurrentRow.strainCode,
    strainName: strainCurrentRow.strainName,
    handleType: '3',
    cultureMediumId: stepNodeObj.cultureMedium,
    culCombinaNo: stepNodeObj.culCombinaNo,
    descText: item.proResultNa
  };
  bacStainingResultList.push(addQcItem);

  if (bacStainingResultList.length > 0) {
    const url = '/api/bac/bac-staining-result/batchAddBacStainingResult';
    proxy.$http
      .post(url, bacStainingResultList)
      .then((res: any) => {
        findStainingResult(strainCurrentRow); // 刷新结果表格
        //courseRecord('继续培养');
        /* if (res && res.status && res.status.code === 1) {
           const a = localStorage.getItem('userInfo');
           const b = JSON.parse(a);
           courseRecord(`【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】继续培养:${item.proResultNa}`);
         }*/
        VxeMessage(res.status.msg, VxeNotifyType.success);
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  } else {
    VxeMessage('请选择要添加的数据', VxeNotifyType.error);
  }
}

// 弹框保存的确定按钮
function saveBacthStaining() {
  if (IsEmpty(radioValue.value)) {
    VxeMessage('请先选择培养基', VxeNotifyType.error);
    return;
  }
  const bacStainingResultList = [];
  const ids = [];
  if (radio1.value == '0') {
    const methodSelectRows = (proxy.$refs.methodTableRef as any).getCheckboxRecords();
    const selectRows = (proxy.$refs.conclusionTableRef as any).getCheckboxRecords();
    if (selectRows.length > 0) {
      for (const sltRow of selectRows) {
        const mthRow = methodSelectRows.find((n: { methodCode: any; }) => (n.methodCode = sltRow.staMethodNo));
        const addQcItem = {
          sampleda: labMainInfoObj.sampleda,
          rptGroup: labMainInfoObj.rptGroup,
          sampleNo: labMainInfoObj.sampleNo,
          maininfoId: labMainInfoObj.id,
          wkFlwId: stepNodeObj.workFlowId,
          testFlowNo: stepNodeObj.testFlowNo,
          wkFlwNodeId: stepNodeObj.workFlowNodeId,
          testNodeNo: stepNodeObj.nodeNo,
          stainingMethNo: mthRow.methodCode,
          stainingConcNo: sltRow.conclusionCode,
          strainId: strainCurrentRow.id,
          strainNo: strainCurrentRow.strainCode,
          strainName: strainCurrentRow.strainName,
          stainingMethNa: mthRow.methodName,
          stainingConcNa: sltRow.conclusionName,
          handleType: radio1.value,
          cultureMediumId: radioValue.value,
          culMediumNo: radioValue.value,
          stainingMethodId: mthRow.id,
          stainingConclusionId: sltRow.id,
          staConclusionNo: sltRow.conclusionCode,
          descText: mthRow.methodName + ',' + sltRow.conclusionName,
          parentId: methodId.value
        };
        bacStainingResultList.push(addQcItem);
        ids.push(sltRow.id);
      }
    }
  } else {
    const cultureCombinationRows = (proxy.$refs.cultureCombinationRef as any).getCheckboxRecords();

    if (cultureCombinationRows.length > 0) {
      for (const sltRow of cultureCombinationRows) {
        const addQcItem = {
          sampleda: labMainInfoObj.sampleda,
          rptGroup: labMainInfoObj.rptGroup,
          sampleNo: labMainInfoObj.sampleNo,
          maininfoId: labMainInfoObj.id,
          wkFlwId: stepNodeObj.workFlowId,
          testFlowNo: stepNodeObj.testFlowNo,
          wkFlwNodeId: stepNodeObj.workFlowNodeId,
          testNodeNo: stepNodeObj.nodeNo,
          strainId: strainCurrentRow.id,
          strainNo: strainCurrentRow.strainCode,
          strainName: strainCurrentRow.strainName,
          handleType: radio1.value,
          cultureMediumId: radioValue.value,
          culMediumNo: radioValue.value,
          combinationId: sltRow.id,
          culCombinaNo: sltRow.id,
          descText: sltRow.name,
          parentId: methodId.value
        };
        bacStainingResultList.push(addQcItem);
      }
    }
  }
  const pyjStr = bacCultureCombinationList.filter(p => p.id === radioValue.value).map(p => p.cultrueNa).join(' ');
  const centStr = bacStainingResultList.map(p => p.descText).join('\n');
  let actStr = '';
  if (!IsEmpty(radio1.value) && radio1.value === '0') {
    actStr = `【涂片】`;
  }
  if (!IsEmpty(radio1.value) && radio1.value === '1') {
    actStr = `【分纯】`;
  }
  if (!IsEmpty(radio1.value) && radio1.value === '2') {
    actStr = `【转种】`;
  }
  if (bacStainingResultList.length > 0) {
    const url = '/api/bac/bac-staining-result/batchAddBacStainingResult';
    proxy.$http
      .post(url, bacStainingResultList)
      .then((res: any) => {
        findStainingResult(strainCurrentRow); // 刷新结果表格
        if (res && res.status && res.status.code === 1) {
          /*   try {
               const a = localStorage.getItem('userInfo');
               const b = JSON.parse(a);
               const contentSrr = [
                 `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】添加步骤\n`,
                 !IsEmpty(pyjStr) ? '培养基: ' + pyjStr + '' : '',
                 !IsEmpty(actStr) ? '' + actStr + '' : '',
                 !IsEmpty(centStr) ? '' + centStr + '' : ''
               ].filter(Boolean).join('\n');
               courseRecord(`${contentSrr}`);
             } catch (error) { }*/
        }
        VxeMessage(res.status.msg, VxeNotifyType.success);
        radio1.value = '0';
      })
      .catch((err: any) => {
        radio1.value = '0';
        VxeMessage(err, VxeNotifyType.error);
      });
  } else {
    VxeMessage('请选择要添加的数据', VxeNotifyType.error);
  }
  radioValue.value = '';
  findCultureInfo();
  closeDialog();
}

//查询菌株下的形态
function findBacOvserResult(strain: { strainCode: any; }) {
  let data = {
    maininfoId: labMainInfoObj.id,
    wkFlwId: stepNodeObj.workFlowId,
    wkFlwNodeId: stepNodeObj.workFlowNodeId,
    isolateNum: strain.strainCode,
    rptGroup: labMainInfoObj.rptGroup,
    sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
    sampleNo: labMainInfoObj.sampleNo,
    testFlowNo: stepNodeObj.testFlowNo,
    testNodeNo: stepNodeObj.nodeNo
  };
  formData.morphologyName = '';
  const url = '/api/bac/bac-obser-result/findBacObserResultList';
  proxy.$http
    /**注意此处的数据条数*/
    .get(url, { params: data })
    .then(async (res: any) => {
      if (res.data[0]) {
        // formData.morphologyName = res.data[0].morphologyName;
        // formData.strainCount = res.data[0].strainCount;
        // formData.bacRate = res.data[0].bacRate;
        // formData.experiment = res.data[0].experiment;
        // formData.isAlarm = res.data[0].isAlarm;
        // formData.alarmText = res.data[0].alarmText;
        Object.assign(formData, res.data[0]);
      }
    })
    .catch((err: any) => {
      VxeMessage('获取形态数据异常', VxeNotifyType.error);
    });
}
// 弹框取消按钮
function closeDialog() {
  showDialog.value = false;
  dialog.value = false;
}

//查询菌株下的染色结果
function findStainingResult(strain: { strainCode: any; }) {
  let data = {
    strainId: strain.strainCode,
    rptGroup: labMainInfoObj.rptGroup,
    sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
    sampleNo: labMainInfoObj.sampleNo
  } as any;
  stainingResultList.length = 0; /**放入数据前清空数据*/
  const url = '/api/bac/bac-staining-result/findBacStainingResultListByStrain';
  proxy.$http
    /**注意此处的数据条数*/
    .get(url, { params: data })
    .then((res: any) => {
      stainingResultList.push(...res.data);
      Object.assign(stainingMethodRow, stainingResultList);
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取染色结果列表数据异常', VxeNotifyType.error);
    });
}

let stainingResultTableDate: any = reactive([]); //弹框表格数据
//染色结果表格单点事件
function stainingMethodCellClick({ row }) {
  Object.assign(stainingResultTableDate, row);
}

//染色结果选中事件
function SelectRowClick(e: { resultCode: any; resultName: any; id: any; }, rowIndex: any) {
  const bacStainingResult = {
    id: stainingResultTableDate.id,
    stainingConcOptNo: e.resultCode,
    stainingConcOptNa: e.resultName,
    stainingOptionsId: e.id
  };
  const url = '/api/bac/bac-staining-result/updateBacStainingResult';
  proxy.$http
    /**注意此处的数据条数*/
    .post(url, bacStainingResult)
    .then(async (res: any) => {
      findStainingResult(strainCurrentRow);
      // courseRecord(`修改${e.resultName}结果`);
      VxeMessage('添加结果成功', VxeNotifyType.success);
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取染色结果列表数据异常', VxeNotifyType.error);
    });
}

/**鉴定结果选中事件 */
function SelectRowClick1(e: { isChild: any; aimKeys: any[]; childIndex: string | number; row: { [x: string]: any; }; }) {
  if (e.isChild) {
    e.aimKeys.forEach((m: { aimKey: string | number; rowKey: string | number; }) => {
      formData[e.childIndex][m.aimKey] = e.row[m.rowKey];
    });
  } else {
    e.aimKeys.forEach((m: { aimKey: string | number; rowKey: string | number; }) => {
      formData[m.aimKey] = e.row[m.rowKey];
    });
  }
}

// function updateBacStainingResult(bacStainingResult) {
//   //todo
// }

function selectChange(value: any) {
  radio1.value = value.value;
  if (value.value === '0') {
    boolFlag.value = true;
    findStainingMethod();
  } else {
    boolFlag.value = false;
    findCultureCombination();
  }
  showDialog.value = true;
}

function radioChange(value: string) {
  if (value == '0') {
    boolFlag.value = true;
    findStainingMethod();
  } else {
    boolFlag.value = false;
    findCultureCombination();
  }
}

function getIsStaticStatusDesc(row: number) {
  if (row == 0) {
    return '涂片';
  } else if (row == 1) {
    return '分纯';
  } else if (row == 2) {
    return '转种';
  } else if (row == 3) {
    return '续培';
  } else {
    return '';
  }
}

//根据字典ID查询报表
function getReportId() {
  const url = '/api/pubReport/getReportByReportCode';
  proxy.$http
    .get(url, { params: { reportCode: '1780416467894419456' } })
    .then((res: any) => {
      reportId.value = res.data;
      // workGroupList.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

//历史回顾传值
function getBacHistories() {
  BacHistoriesLeftRef.value?.initPage(labMainInfoObj);
}

/**静默打印执行打印 */
function publishSecReport() {
  const rows = bacDrugTestResultRef.value?.getCheckboxRecords(true);

  if (!IsEmpty(secReportMustSelectStaing.value) && (secReportMustSelectStaing.value === '1' || secReportMustSelectStaing.value === 1)) {
    if (!rows || rows.length <= 0) {
      VxeMessage('请先勾选染色方法', VxeNotifyType.warning);
      return;
    }
  }
  secReportDialog.value = true;
  proxy.$nextTick(() => {
    refBacSecReport.value?.initPage(labMainInfoObj, formData, rows);
  });
}
/**撤销涂片报告*/
function revokeSecReport() {

  if (!strainCurrentRow || IsEmpty(strainCurrentRow.strainCode)) {
    proxy.$alert("请先新增【菌株】", "提示");
    return;
  }
  proxy
    .$confirm('确定撤销涂片报告？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const data = {
        rptGroup: labMainInfoObj.rptGroup,
        sampleda: labMainInfoObj.sampleda + ' 00:00:00',
        sampleNo: labMainInfoObj.sampleNo,
        testFlowNo: stepNodeObj.testFlowNo,
        testNodeNo: stepNodeObj.nodeNo,
        strainNo: strainCurrentRow.strainCode
      };

      const url = '/api/bac/bacPublisSecReport/batchEditRevokeSecReport';
      proxy.$http
        .post(url, data)
        .then((res: any) => {
          VxeMessage('撤销成功', VxeNotifyType.success);
          if (res && res.status && res.status.code === 1) {
            if (formData && !IsEmpty(formData.isolateNum)) {
              formData.bacPublishStatus = 0;
            }
            try {
              const a = localStorage.getItem('userInfo');
              const b = JSON.parse(a);
              const contentSrr = [
                `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】撤销图片报告报告\n`
              ].filter(Boolean).join('\n');
              courseRecord(`${contentSrr}`);
            } catch (err) { }
          }
          secReportDialog.value = false;
        })
        .catch((err: any) => {
          VxeMessage('发布失败', VxeNotifyType.success);
        });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

/*function confirmSecReport() {
  const datas: { rptGroup: any; sampleda: string; sampleNo: any; testFlowNo: any; testNodeNo: any; strainNo: any; stainingResulId: any; }[] = [];
  const rows = bacDrugTestResultRef.value?.getCheckboxRecords(true);
  if (rows && rows.length > 0) {
    const descStrs: any[] = [];
    rows.forEach((element: { id: any; stainingConcNa: any; }) => {
      const data = {
        rptGroup: labMainInfoObj.rptGroup,
        sampleda: labMainInfoObj.sampleda + ' 00:00:00',
        sampleNo: labMainInfoObj.sampleNo,
        testFlowNo: stepNodeObj.testFlowNo,
        testNodeNo: stepNodeObj.nodeNo,
        strainNo: strainCurrentRow.strainCode,
        stainingResulId: element.id
      };
      descStrs.push(element.stainingConcNa);
      datas.push(data);
    });
    const url = '/api/bac/bacPublisSecReport/batchEditPublisSecReport';
    proxy.$http
      .post(url, datas)
      .then((res: any) => {
        VxeMessage('发布成功', VxeNotifyType.success);
        if (res && res.status && res.status.code === 1) {
          try {
            const a = localStorage.getItem('userInfo');
            const b = JSON.parse(a);
            const contentSrr = [
              `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】发布二级报告\n`,
              !IsEmpty(formData.morphologyName) ? '结果描述: ' + formData.morphologyName + '' : '',
              descStrs && descStrs.length > 0 ? '染色结果: ' + (descStrs.join(',')) + '' : '',
            ].filter(Boolean).join('\n');
            courseRecord(`${contentSrr}`);
          } catch (err) { }
        }
        secReportDialog.value = false;
      })
      .catch((err: any) => {
        VxeMessage('发布失败', VxeNotifyType.success);
      });
  }
}*/
/* 确认发布二级报告 */
function confirmSecReportV1() {
  const datas: { rptGroup: any; sampleda: string; sampleNo: any; testFlowNo: any; testNodeNo: any; strainNo: any; stainingResulId: any; }[] = [];
  const rows = bacDrugTestResultRef.value?.getCheckboxRecords(true);
  if (rows && rows.length > 0) {
    const descStrs: any[] = [];
    rows.forEach((element: { id: any; descText: any; }) => {
      const data = {
        rptGroup: labMainInfoObj.rptGroup,
        sampleda: labMainInfoObj.sampleda + ' 00:00:00',
        sampleNo: labMainInfoObj.sampleNo,
        testFlowNo: stepNodeObj.testFlowNo,
        testNodeNo: stepNodeObj.nodeNo,
        strainNo: strainCurrentRow.strainCode,
        stainingResulId: element.id
      };
      datas.push(data);
      descStrs.push(element.descText);
    });
    const url = '/api/bac/bacPublisSecReport/batchEditPublisSecReport';
    proxy.$http
      .post(url, datas)
      .then((res: any) => {
        VxeMessage('发布成功', VxeNotifyType.success);
        if (res && res.status && res.status.code === 1) {
          if (formData && !IsEmpty(formData.isolateNum)) {
            formData.bacPublishStatus = 1;
          }
          try {
            const a = localStorage.getItem('userInfo');
            const b = JSON.parse(a);
            const contentSrr = [
              `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】发布二级报告\n`,
              !IsEmpty(formData.morphologyName) ? '结果描述: ' + formData.morphologyName + '' : '',
              descStrs && descStrs.length > 0 ? '染色结果: ' + (descStrs.join(',')) + '' : '',
            ].filter(Boolean).join('\n');
            courseRecord(`${contentSrr}`);
          } catch (err) { }
        }
        secReportDialog.value = false;
      })
      .catch((err: any) => {
        VxeMessage('发布失败', VxeNotifyType.success);
      });
  } else {
    const data = {
      rptGroup: labMainInfoObj.rptGroup,
      sampleda: labMainInfoObj.sampleda + ' 00:00:00',
      sampleNo: labMainInfoObj.sampleNo,
      testFlowNo: stepNodeObj.testFlowNo,
      testNodeNo: stepNodeObj.nodeNo,
      strainNo: strainCurrentRow.strainCode,
      stainingResulId: ''
    };
    datas.push(data);
    const descStrs: any[] = [];
    const url = '/api/bac/bacPublisSecReport/batchEditPublisSecReport';
    proxy.$http
      .post(url, datas)
      .then((res: any) => {
        VxeMessage('发布成功', VxeNotifyType.success);
        if (res && res.status && res.status.code === 1) {
          if (formData && !IsEmpty(formData.isolateNum)) {
            formData.bacPublishStatus = 1;
          }
          try {
            const a = localStorage.getItem('userInfo');
            const b = JSON.parse(a);
            const contentSrr = [
              `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】发布二级报告\n`,
              !IsEmpty(formData.morphologyName) ? '结果描述: ' + formData.morphologyName + '' : '',
              descStrs && descStrs.length > 0 ? '染色结果: ' + (descStrs.join(',')) + '' : '',
            ].filter(Boolean).join('\n');
            courseRecord(`${contentSrr}`);
          } catch (err) { }
        }
        secReportDialog.value = false;
      })
      .catch((err: any) => {
        VxeMessage('发布失败', VxeNotifyType.success);
      });
  }
}

//染色方法 右侧表格勾选 左侧父级表格自动勾选
function onConclusionCheckboxChange(checkedRows: { records: any[]; }) {
  if (checkedRows.records.length > 0) {
    // 如果右侧 有勾选数据
    checkedRows.records.forEach((row: { stainingMethodId: any; }) => {
      // 在左侧表格数据中查找相同数据
      let leftTableRow = methodTableData.find((item: { id: any; }) => item.id === row.stainingMethodId);
      if (leftTableRow) {
        // 将左侧表格中对应行的勾选状态设为 true
        proxy.$refs.methodTableRef.setCheckboxRow(leftTableRow, true);
      }
    });
  } else {
    //如果右侧表格没有任何行被勾选 将左侧表格中对应行的勾选状态设为 false
    proxy.$refs.methodTableRef.setCheckboxRow(leftCurrentRow, false);
  }
}

function courseRecord(val: string) {
  const a = localStorage.getItem('userInfo');
  const b = JSON.parse(a);
  const row = {
    strainId: strainCurrentRow.id,
    strainNo: strainCurrentRow.strainCode,
    strainName: strainCurrentRow.strainName,
    maininfoId: labMainInfoObj.id,
    wkFlwId: stepNodeObj.workFlowId,
    wkFlwNodeId: stepNodeObj.workFlowNodeId,
    rptGroup: labMainInfoObj.rptGroup,
    sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
    sampleNo: labMainInfoObj.sampleNo,
    testFlowNo: stepNodeObj.testFlowNo,
    testNodeNo: stepNodeObj.nodeNo,
    content: val,
    operatorDoctor: IsEmpty(b.username) ? '' : b.username
  };

  const url = '/bac/strainLog/addStrainLog';
  proxy.$http
    .post(url, row)
    .then((res: any) => {
      // VxeMessage('新增成功', VxeNotifyType.success);
    })
    .catch((err: any) => {
      VxeMessage('新增失败', VxeNotifyType.success);
    });
  // setTimeout(() => {
  //   findRptCultiObserResult('0');
  // }, 500);
}

/**染色结果行颜色判断 */
function stainingResultCellColor({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
  if (row && row.isAlarm && (row.isAlarm === 1 || row.isAlarm === '1')) {
    return { color: '#ff0000' };
  }
}

/**选择染色结果   发布危急值  复选框选择改变事件 */
function criValueChange({ checked, $event }) {
  if (checked && currentStainResult.isPushSecReport !== 1) {
    currentStainResult.isPushSecReport = 1;
  }
}
/**加载图片列表组件数据 */
function loadImgsCallback() {
  proxy.$emit('imageUploadSuccess');
}
/**镜检截图组件弹窗 */
function imageSelection() {
  if (IsEmpty(strainCurrentRow)) {
    VxeMessage('无菌株，请新增菌株', VxeNotifyType.error);
    return;
  }

  BacCultiObserImageResultRef.value?.initPage(labMainInfoObj, { testFlowNo: stepNodeObj.testFlowNo, testNodeNo: stepNodeObj.nodeNo, isolateNum: strainCurrentRow.strainCode, germNo: '' });
}
/**镜检截图选中回调 */
function imgSelectedCallback() {
  srcList.length = 0;
  previewSrcList.length = 0;
  const url = '/api/bac/bac-image-result/findBacImageResultList';
  proxy.$http
    .get(url, {
      params: {
        rptGroup: labMainInfoObj.rptGroup,
        sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
        sampleNo: labMainInfoObj.sampleNo,
        testFlowNo: IsEmpty(stepNodeObj.testFlowNo) ? null : stepNodeObj.testFlowNo,
        testNodeNo: IsEmpty(stepNodeObj.nodeNo) ? null : stepNodeObj.nodeNo,
        isolateNum: IsEmpty(strainCurrentRow.strainCode) ? null : strainCurrentRow.strainCode,
        isSelected: 1
      }
    })
    .then(async (res: any) => {
      if (!IsEmpty(res.data) && res.data) {
        Object.assign(srcList, res.data);
        //循环读取srcList中的图片路径，存储到previewSrcList中
        srcList.forEach((item) => {
          previewSrcList.push(combinePicPath(item));
        });
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
/**截图路径 */
function combinePicPath(item: never) {
  return `${(window as any).apiUrl.VITE_SERVER_URL}${item.imageUrl}`;
}
/**预览初级报告 */
//增加菌株匹配选择，若菌株号存在，则匹配
function previewSecondRpt() {
  proxy.$emit('actionBtnsClick', { event: 'previewSecondRpt', paramObj: { testFlowNo: stepNodeObj.testFlowNo, testNodeNo: stepNodeObj.nodeNo, strainNo: strainCurrentRow.strainCode } });
}
/**打印二级报告 */
function printSecondRpt() {
  proxy.$emit('actionBtnsClick', { event: 'printSecondRpt', paramObj: { testFlowNo: stepNodeObj.testFlowNo, testNodeNo: stepNodeObj.nodeNo } });
}
/**工作单 */
function reprintLabel() {
  const url = '/api/lab/lab-rptmain/RePrintLabel';
  proxy.$http
    .get(url, { params: { sltWorkFlowNo: sltWorkFlowObj._value.workFlowNo } }).then(async (res: any) => {
      if (res.status && res.status.code === 1) {
        printParamsObj.value = [{ ReportName: res.data.reportId, ReportParameters: [{ Name: 'reqNo', Value: labMainInfoObj.reqNo }, { Name: 'Id', Value: labMainInfoObj.id }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }];
        // const a = localStorage.getItem('userInfo');
        // const b = JSON.parse(a);
        // courseRecord(`【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】打印工作单:${labMainInfoObj.reqNo}`);
      }
    }).catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

/**判断是否审核，若审核范围ture */
function resultIsDisabled() {
  if (!IsEmpty(labMainInfoObj) && labMainInfoObj.isChk == '2') {
    return true;
  } else {
    return false;
  }
}
/**危急值 */
function criticalClick() {
  criticalObserReportRef.value?.criticaReportData(labMainInfoObj, stepNodeObj, currentStainResult);
}
/**危急值处理完成 */
function alarmTreatFinish(data: any[]) {
  /* if (alarmReportBeforeChk.value && !chkBeforePrint.value) {
     $this['chkMainInfo']();
   }
   if (alarmReportBeforeChk.value && chkBeforePrint.value) {
     $this['previewPrint']();
   }*/
  try {
    const a = localStorage.getItem('userInfo');
    const b = JSON.parse(a);

    const cntStrArr = [`【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】发布危急值\n`];
    data.forEach((itm: { criItem: { isolateNum: any; morphologyName: any; strainCount: any; alarmText: any; }; criData: { notifyPersonNa: any; reportPersonNa: any; notificationTypeNa: any; remark: any; }; }) => {
      if (itm.criItem) {
        if (!IsEmpty(itm.criItem.isolateNum)) {
          cntStrArr.push(`【第${itm.criItem.isolateNum}珠菌】`);
        }
        if (!IsEmpty(itm.criItem.morphologyName)) {
          cntStrArr.push(`结果描述: ${itm.criItem.morphologyName}`);
        }
        if (!IsEmpty(itm.criItem.strainCount)) {
          cntStrArr.push(`菌落计数: ${itm.criItem.strainCount}`);
        }
        if (!IsEmpty(itm.criItem.alarmText)) {
          cntStrArr.push(`危急值描述: ${itm.criItem.alarmText}`);
        }

      }
      if (itm.criData) {
        if (!IsEmpty(itm.criData.notifyPersonNa)) {
          cntStrArr.push(`通知医师:${itm.criData.notifyPersonNa}`);
        }
        if (!IsEmpty(itm.criData.reportPersonNa)) {
          cntStrArr.push(`发布人:${itm.criData.reportPersonNa}`);
        }
        if (!IsEmpty(itm.criData.notificationTypeNa)) {
          cntStrArr.push(`通知方式:${itm.criData.notificationTypeNa}`);
        }
        if (!IsEmpty(itm.criData.remark)) {
          cntStrArr.push(`备注:${itm.criData.remark}`);
        }
      }
      if (cntStrArr && cntStrArr.length > 0) {
        cntStrArr.push(`\n`);
      }
    });

    const cntStr = cntStrArr.filter(Boolean) // 过滤掉空字符串
      .join('\n');

    courseRecord(`${cntStr}`);
  } catch (error) { }
}

function germAlarmConfirm(value: any) {
  formData.alarmText = value;
}
/* 查询历史报告 */
function rptSecondReportHistory() {
  const rows = bacDrugTestResultRef.value?.getCheckboxRecords(true);
  BacSecondReportHistoryRef.value?.initPage(labMainInfoObj, formData, rows, currentStainResult);
}

function openDialog() {
  getCultureDetail();
  dialog.value = true;
}


// 加载培养基
function getCultureDetail() {
  if (!labMainInfoObj.reqNo) {
    return;
  }
  cultureTableList.length = 0;
  lloading.value = true;
  const url = '/api/bac/bac-test-culture-medium/findBacTestCultureMediumList';
  proxy.$http
    .get(url, { params: { reqNo: labMainInfoObj.reqNo } })
    .then(async (res: any) => {
      Object.assign(cultureTableList, res.data);
      //默认全选
      proxy.$nextTick(() => {
        const $xTable = proxy.$refs.cultureTableRef as any;
        if (cultureTableList && cultureTableList.length > 0) {
          $xTable.setCheckboxRow(cultureTableList, true);
          //$xTable.updateFooter(); // 在值发生改变时更新表尾合计(一开始获取页面信息时调用计算表尾方法)
        }
      });
      lloading.value = false;
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

function printLabel() {
  const selectRows = (proxy.$refs.cultureTableRef as any).getCheckboxRecords();
  let reportId: any;
  if (selectRows.length > 0) {
    let url = `/api/pubReport/getReportByBusFormCode?code=006`;
    proxy.$http
      .get(url)
      .then((res: any) => {
        if (res && res.status && res.status.code === 1 && res.data && !IsEmpty(res.data.id)) {
          reportId = res.data.id;
          let i = 0;
          selectRows.forEach((sltRow: any) => {
            if (!sltRow.isPrintLabels) {
              let num = 1;
              let report = reportId;
              if (!IsEmpty(sltRow.tagsNum)) {
                num = sltRow.tagsNum;
              }
              if (!IsEmpty(sltRow.mediumTag)) {
                report = sltRow.mediumTag;
              }
              const param = [{ ReportName: report, ReportParameters: [{ Name: 'code', Value: labMainInfoObj.reqNo }], PdfPrinterSetting: { PdfPrinterCopies: num } }];
              setTimeout(() => {
                quietPrintRef.value?.print2(param);
              }, i * 100);
              i++;
            }
          })
        } else {
          proxy.$alert('查无报告模板', '提示');
        }
      })
      .catch((err: any) => {
        proxy.$alert('查询报告模板失败' + err, '提示');
        //VxeMessage('操作失败,请联系管理员', VxeNotifyType.error);
      });
  }
  dialog.value = false;
}

//自动打印标签
function autoPrintLabel() {
  console.log('自动打印标签====>>>>>');
  
  if (!labMainInfoObj.reqNo) {
    return;
  }
  cultureTableList.length = 0;
  const url = '/api/bac/bac-test-culture-medium/findBacTestCultureMediumList';
  proxy.$http
    .get(url, { params: { reqNo: labMainInfoObj.reqNo } })
    .then(async (res: any) => {
      Object.assign(cultureTableList, res.data);

      let reportId: any;
      if (cultureTableList.length > 0) {
        let url = `/api/pubReport/getReportByBusFormCode?code=006`;
        proxy.$http
          .get(url)
          .then((res: any) => {
            if (res && res.status && res.status.code === 1 && res.data && !IsEmpty(res.data.id)) {
              reportId = res.data.id;
              let i = 0;
              cultureTableList.forEach((sltRow: any) => {
                if (!sltRow.isPrintLabels) {
                  let num = 1;
                  let report = reportId;
                  if (!IsEmpty(sltRow.tagsNum)) {
                    num = sltRow.tagsNum;
                  }
                  if (!IsEmpty(sltRow.mediumTag)) {
                    report = sltRow.mediumTag;
                  }
                  const param = [{ ReportName: report, ReportParameters: [{ Name: 'code', Value: labMainInfoObj.reqNo }], PdfPrinterSetting: { PdfPrinterCopies: num } }];
                  setTimeout(() => {
                    quietPrintRef.value?.print2(param);
                  }, i * 100);
                  i++;
                }
              })
            } else {
              proxy.$alert('查无报告模板', '提示');
            }
          })
          .catch((err: any) => {
            proxy.$alert('查询报告模板失败' + err, '提示');
            //VxeMessage('操作失败,请联系管理员', VxeNotifyType.error);
          });
      }
     
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}


function experimentClick() {
  getExperiment();
  exDialog.value = true;
}

// 加载生化实验
function getExperiment() {
  exTableList.length = 0;
  exloading.value = true;
  const url = '/api/bac/bac-experiment/findBacExperimentList';
  proxy.$http
    .get(url, { params: "" })
    .then(async (res: any) => {
      Object.assign(exTableList, res.data);
      exloading.value = false;
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

function closeExDialog() {
  exDialog.value = false;
}

function confirm() {
  const selectRows = (proxy.$refs.exTableRef as any).getCheckboxRecords();
  if (selectRows.length > 0) {
    if (!strainCurrentRow || IsEmpty(strainCurrentRow.strainCode)) {
      proxy.$alert("请先新增【菌株】", "提示");
      return;
    }

    console.log('selectRows', selectRows);


    let data = '';
    //循环selectRows
    selectRows.forEach((item: any) => {
      data += item.name + ';';
    });

    if (!IsEmpty(formData.experiment)) {
      formData.experiment = formData.experiment + '\n' + data;
    } else {
      formData.experiment = data;
    }
    if (labMainInfoObj.id && stepNodeObj.testFlowNo && stepNodeObj.nodeNo && strainCurrentRow.id) {
      const data = {
        id: formData.id,
        maininfoId: labMainInfoObj.id,
        wkFlwId: stepNodeObj.workFlowId,
        wkFlwNodeId: stepNodeObj.workFlowNodeId,
        isolateNum: strainCurrentRow.strainCode,
        experiment: formData.experiment,
        sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
        rptGroup: labMainInfoObj.rptGroup,
        sampleNo: labMainInfoObj.sampleNo,
        testFlowNo: stepNodeObj.testFlowNo,
        isAlarm: formData.isAlarm,
        testNodeNo: stepNodeObj.nodeNo
      };
      const url = '/api/bac/bac-obser-result/saveOrUpdateBacObserResult';
      proxy.$http
        .post(url, data)
        .then((res: any) => {
          VxeMessage(res.status.msg, VxeNotifyType.success);
          if (res && res.status && res.status.code == 1) {
            //Object.assign(formData, res.data);   
            bacCultiObserItemClick(strainCurrentRow);
          }
        })
        .catch((err: any) => {
          VxeMessage(err, VxeNotifyType.error);
        });
    }

  }
  exDialog.value = false;
}

</script>

<style scoped lang="scss">
@import '@/assets/css/el-tabs.scss';

#rptCultiObserResult {
  height: 100%;
}

#transResult {
  height: 100%;
}

.lab-bac-test-result-tab {
  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }

  :deep(.el-tabs__nav-prev) {
    line-height: 28px !important;
  }

  :deep(.el-tabs__nav-next) {
    line-height: 28px !important;
  }

  :deep(.el-tabs__content) {
    height: 0px;
    padding: 2px;
  }

  :deep(.el-tab-pane) {
    height: 0px;
  }
}

:deep(.cell-bgColor) {
  .vxe-cell {
    height: 100%;
  }
}

:deep(.el-step__line) {
  display: none;
}

:deep(.el-step) {
  cursor: pointer;
}

:deep(.el-step__title) {
  font-size: 12px;
  line-height: 2em;
}

// 染色方法弹框
.dyeingMethodDialog {
  .dialogHeader {
    .headerTitle {
      font-size: 20px;
    }

    .headerRadioGroup {
      margin: 5px 0 0 10px;
    }
  }

  .dialogBody {
    .bodyRadioGroup {
      margin: 0 0 10px 10px;
    }

    .tablesDiv {
      height: 400px;
    }
  }
}

:deep(.el-dialog__body) {
  padding: 10px 0 0 10px;
}

:deep(.el-divider--horizontal) {
  margin: 12px 0;
}

:deep(.el-step__icon) {
  background: rgba(0, 0, 0, 0) !important;
}

.no-edit {
  user-select: none;
  /* 禁止选择文本 */
  pointer-events: none;
  /* 禁止所有鼠标事件 */
}</style>
